﻿using Prism.Commands;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using 基于WPF的电缆采样数据分析系统.Models.Dbs;
using 基于WPF的电缆采样数据分析系统.Models.Dbs.DbService;
using 基于WPF的电缆采样数据分析系统.Service;
using 基于WPF的电缆采样数据分析系统.Tools.LangugeTool;
using 基于WPF的电缆采样数据分析系统.Tools.MessagePopupTool;
using 基于WPF的电缆采样数据分析系统.Models.Enums;

namespace 基于WPF的电缆采样数据分析系统.ViewModels.Settings
{
    public class SysSetUCViewModel : BindableBase
    {

        /// <summary>
        /// 对话服务
        /// </summary>
        private readonly DialogHostService DialogHostService;

        /// <summary>
        /// 构造器
        /// </summary>
        public SysSetUCViewModel()
        {
            // 管理员权限时显示用户数据
            if (GlobalVariableEdit.CurrentUserInfo.GradeId == 1)
            {
                UserInfoList = UserService.Instance.GetAllNormalUserList();
            }

            DialogHostService = App.GetService<DialogHostService>();

            // 生成邀请码
            GenerateInvitationCodeCmm = new DelegateCommand(GenerateInvitationCodeFun);

            // 复制邀请码
            CopyInvitationCodeCmm = new DelegateCommand(CopyInvitationCodeFun);

            // 操作用户
            OperationBtnUserCmm = new DelegateCommand<int?>(OperationBtnUserFun);

            // 删除用户
            DeleteUserCmm = new DelegateCommand<int?>(DeleteUserFun);
        }



        #region 生成邀请码

        /// <summary>
        /// 邀请码
        /// </summary>
        private string _InvitationCode;

        /// <summary>
        /// 邀请码
        /// </summary>
        public string InvitationCode
        {
            get { return _InvitationCode; }
            set { 
                _InvitationCode = value;
                RaisePropertyChanged();
            }
        }



        /// <summary>
        /// 生成邀请码
        /// </summary>
        public DelegateCommand GenerateInvitationCodeCmm { get; set; }

        /// <summary>
        /// 生成邀请码
        /// </summary>
        private void GenerateInvitationCodeFun()
        {
            
            bool IsGenerateSuccess = true;

            while (IsGenerateSuccess)
            {
                InvitationCode = GenerateRandomString(10); // 生成长度为10的随机字符串

                // 验证邀请码是否已存在
                int result = InvitationCodeRecordService.Instance.IsInvitationCodeExist(InvitationCode);

                if (result == 0)
                {
                    IsGenerateSuccess = false;
                }
            }

            // 注册邀请码
            InvitationCodeRecordService.Instance.GenerateInvitationCode(InvitationCode);

            // 消息提示
            MessagePopup.DisplayMessagePopup(LangugeConvertor.GetValue("TheInvitationCodeIsGeneratedCuccessfullyProcedure"));
        }

        


        /// <summary>
        /// 根据长度随机生成一段字符串
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        public string GenerateRandomString(int length)
        {
            const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
            Random random = new Random();
            return new string(Enumerable.Repeat(chars, length)
                .Select(s => s[random.Next(s.Length)]).ToArray());
        }

        #endregion


        #region 复制邀请码

        /// <summary>
        /// 复制邀请码
        /// </summary>
        public DelegateCommand CopyInvitationCodeCmm { get; set; }

        /// <summary>
        /// 复制邀请码
        /// </summary>
        private void CopyInvitationCodeFun()
        {
            CopyToClipboard(InvitationCode); // 调用方法复制到剪贴板

            // 消息提示
            MessagePopup.DisplayMessagePopup(LangugeConvertor.GetValue("CopyingTheInvitationCodeSucceededProcedure"));
        }


        public void CopyToClipboard(string text)
        {
            // 确保运行在 STA（单线程单元）模式下，否则可能会抛出异常
            if (string.IsNullOrEmpty(text))
            {
                Console.WriteLine("无法复制空文本！");
                return;
            }

            try
            {
                Clipboard.SetText(text); // 将文本设置到剪贴板
            }
            catch (Exception ex)
            {
                Console.WriteLine($"复制失败：{ex.Message}");
            }
        }
        #endregion


        #region 注册用户信息

        /// <summary>
        /// 用户信息集合
        /// </summary>
        private ObservableCollection<User> _UserInfoList;

        /// <summary>
        /// 用户信息集合
        /// </summary>
        public ObservableCollection<User> UserInfoList
        {
            get { return _UserInfoList; }
            set { 
                _UserInfoList = value;
                RaisePropertyChanged();
            }
        }

        /// <summary>
        /// 操作用户
        /// </summary>
        public DelegateCommand<int?> OperationBtnUserCmm { get; set; }

        /// <summary>
        /// 操作用户
        /// </summary>
        private async void OperationBtnUserFun(int? uid)
        {
            DialogParameters paras = new DialogParameters();

            User user = UserService.Instance.GetUserByUid((int)uid);

            if (user != null)
            {
                if (user.IsEnable == 1)
                {
                    paras.Add("title", LangugeConvertor.GetValue("DisablePage"));
                    paras.Add("Text1", LangugeConvertor.GetValue("DoYouWantToDisable"));
                    paras.Add("Alias", user.Alias);
                } else if (user.IsEnable == 0)
                {
                    paras.Add("title", LangugeConvertor.GetValue("EnablePage"));
                    paras.Add("Text1", LangugeConvertor.GetValue("DoYouWantToEnable"));
                    paras.Add("Alias", user.Alias);
                }

                var result = await DialogHostService.ShowDialog("UpdateUserUC", paras);

                if (result.Result == ButtonResult.Yes)
                {
                    if (user.IsEnable == 1)
                    {
                        RetResult retResult = UserService.Instance.DisableUserById((int)uid);

                        if (retResult == RetResult.Success)
                        {
                            MessagePopup.DisplayMessagePopup(LangugeConvertor.GetValue("DisablingUserSucceeded"));
                            // 刷新用户集合信息
                            UserInfoList = UserService.Instance.GetAllNormalUserList();
                        }
                    }
                    else if (user.IsEnable == 0)
                    {
                        RetResult retResult = UserService.Instance.EnableUserById((int)uid);

                        if (retResult == RetResult.Success)
                        {
                            MessagePopup.DisplayMessagePopup(LangugeConvertor.GetValue("SucceededInEnablingUser"));
                            // 刷新用户集合信息
                            UserInfoList = UserService.Instance.GetAllNormalUserList();
                        }
                    }
                }
            }

            
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        public DelegateCommand<int?> DeleteUserCmm { get; set; }

        /// <summary>
        /// 删除用户
        /// </summary>
        private async void DeleteUserFun(int? uid)
        {
            User user = UserService.Instance.GetUserByUid((int)uid);

            if (user != null)
            {
                DialogParameters paras = new DialogParameters();
                paras.Add("title", LangugeConvertor.GetValue("DeletePage"));
                paras.Add("Text1", LangugeConvertor.GetValue("DoYouWantToDelete"));
                paras.Add("Alias", user.Alias);

                var result = await DialogHostService.ShowDialog("UpdateUserUC", paras);

                if (result.Result == ButtonResult.Yes)
                {
                    RetResult retResult = UserService.Instance.DeleteUserById((int)uid);

                    if (retResult == RetResult.Success)
                    {
                        MessagePopup.DisplayMessagePopup(LangugeConvertor.GetValue("DisablingUserSucceeded"));
                        // 刷新用户集合信息
                        UserInfoList = UserService.Instance.GetAllNormalUserList();
                    }
                }
            }
        }

        #endregion

    }
}
